<template>
  <div ref="chartRef" :style="{ height, width }"></div>
</template>

<script lang="ts">
  import { defineComponent, PropType, ref, Ref, onMounted, watch, emit } from 'vue';
  import { useECharts } from '/@/hooks/web/useECharts';
  import { registerMap } from 'echarts';

  export default defineComponent({
    props: {
      width: {
        type: String as PropType<string>,
        default: '100%',
      },
      height: {
        type: String as PropType<string>,
        default: 'calc(100vh - 100px)',
      },
      chartData: {
        type: Array as PropType<{ name: string; values: { value: number; tipData: string }[] }[]>,
        required: true,
      },
    },
    emits: ['mapClick'], // 定义自定义事件
    setup(props, { emit }) {
      const chartRef = ref<HTMLDivElement | null>(null);
      const { setOptions, getInstance } = useECharts(chartRef as Ref<HTMLDivElement>);

      onMounted(async () => {
        const json = (await (await import('./xian.json')).default) as any;
        registerMap('XiAn', json);

        // 初始设置选项
        updateChartOptions();
      });

      const updateChartOptions = () => {
        const processedData = props.chartData.flatMap((item) => item.values.map((value) => ({ ...value, name: item.name })));

        setOptions({
          visualMap: [
            {
              min: 0,
              max: 5000,
              left: 'left',
              bottom: '20',
              text: ['高', '低'],
              calculable: false,
              orient: 'horizontal',
              inRange: {
                color: ['#e0ffff', '#006edd'],
                symbolSize: [30, 100],
              },
            },
          ],
          tooltip: {
            trigger: 'item',
            backgroundColor: 'rgba(0, 0, 0, .6)',
            textStyle: {
              color: '#fff',
              fontSize: 12,
            },
            formatter: function (params: any) {
              if (!params.data) return '';
              const { name, values } = props.chartData.find((item) => item.name === params.name) || {};
              if (!values) return '';

              const tooltipContent = values.map((value) => `${value.tipData}: ${value.value}`).join('<br/>');

              return `${name}<br/>${tooltipContent}`;
            },
          },
          series: [
            {
              name: '安装量',
              type: 'map',
              map: 'XiAn',
              label: {
                show: true,
                color: 'rgb(249, 249, 249)',
                fontSize: 10,
              },
              itemStyle: {
                areaColor: '#2f82ce',
                borderColor: '#0DAAC1',
              },
              data: processedData,
            },
          ],
        });

        // 添加点击事件
        const chartInstance = getInstance();
        chartInstance.on('click', (params: any) => {
          console.log('1231233');
          console.log(params.data, '123123555');

          if (params.data) {
            emit('mapClick', params.data.name); // 触发自定义事件并传递区县名称
          }
        });
      };

      // 监听 chartData 变化，更新图表
      watch(
        () => props.chartData,
        () => {
          updateChartOptions();
        }
      );

      return { chartRef };
    },
  });
</script>
